package cn.com.hhrcw.enterprise.web;

import cn.com.hhrcw.enterprise.params.EntryParam;
import cn.com.hhrcw.enterprise.params.OpJobParams;
import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.position.entity.RecruitmentPosition;
import cn.com.hhrcw.position.service.IRecruitmentPositionService;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.utils.DownloadToZipUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 批量下载简历
 *
 * @program: recruit-boot-parent
 * @description:
 * @author: JD
 * @create: 2020-11-24 09:54
 **/
@RestController
@Slf4j
@RequestMapping("/en/download/resume")
@Api(tags = "批量下载简历")
@Validated
public class DownloadResumeController {

    @Autowired
    private ICvResumeService resumeService;

    @Autowired
    private IFileService fileService;

    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ICvUserEduInfoService eduInfoService;

    @Autowired
    private ICvWorkIntentionService workIntentionService;

    @Autowired
    IRecruitmentPositionService positionService;

    @Autowired
    private IEnContactsService enContactsService;

    @Autowired
    private IOpEntryHistoryService entryHistoryService;

    @Autowired
    private IOpInterviewHistoryService interviewHistoryService;

    @Autowired
    private IOpDeliveryHistoryService deliveryHistoryService;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    private IOpJobService opJobService;

    @Autowired
    private ISysUserDepartService userDepartService;

    @Autowired
    IOpShieldingService opShieldingService;

    /**
     * 人才库-人才
     *
     * @param params
     * @return
     */
    List<String> getUserListInfo(EntryParam params) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUserDepart depart = userDepartService.lambdaQuery().eq(SysUserDepart::getUserId, loginUser.getId()).one();
        LambdaQueryWrapper<OpJob> jobLambdaQueryWrapper = new LambdaQueryWrapper<>();
        jobLambdaQueryWrapper.eq(OpJob::getCompanyId, depart.getDepId());
        if (StrUtil.isNotBlank(params.getSsId())) {
            jobLambdaQueryWrapper.eq(OpJob::getBsId, params.getSsId());
        }
        if (StringUtils.isNotBlank(params.getJobId())) {
            jobLambdaQueryWrapper.eq(OpJob::getId, params.getJobId());
        }
        List<OpJob> jobs = opJobService.list(jobLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(jobs)) {
            List<String> jobIds = new ArrayList<>();
            jobs.forEach(e -> {
                jobIds.add(e.getId());
            });
            LambdaQueryWrapper<OpDeliveryHistory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(OpDeliveryHistory::getJobId, jobIds);
            List<OpShielding> shieldingList = opShieldingService.lambdaQuery().eq(OpShielding::getComId, depart.getDepId()).eq(OpShielding::getDelFlag, false).list();
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(shieldingList)) {
                queryWrapper.notIn(OpDeliveryHistory::getUserId, shieldingList.stream().map(OpShielding::getUserId).toArray());
            }
            if (!createOpDeliveryHistoryWrapper(params, queryWrapper)) {
                return new ArrayList<>();
            }
            if (!createOpDeliveryHistoryWrapperTwo(params, queryWrapper)) {
                return new ArrayList<>();
            }
            if (params.getMinWorkYear() != null && params.getMaxWorkYear() != null) {
                LambdaQueryWrapper<PiInfo> infoQuery = new LambdaQueryWrapper<>();
                if (params.getMinWorkYear() != null && params.getMaxWorkYear() != null) {
                    int maxWorkYear = 999;
                    if (params.getMinWorkYear() == 0 && params.getMaxWorkYear() == maxWorkYear) {
                    } else if (params.getMinWorkYear() == 0 && params.getMaxWorkYear() == 0) {
                        infoQuery.isNull(PiInfo::getJobTime);
                    } else {
                        String start = cn.com.hhrcw.utils.DateUtil.getYearFirst(params.getMaxWorkYear());
                        String end = cn.com.hhrcw.utils.DateUtil.getYearLast(params.getMinWorkYear());
                        infoQuery.ge(PiInfo::getJobTime, start).le(PiInfo::getJobTime, end);
                    }
                }
                List<PiInfo> piInfoList = piInfoService.list(infoQuery);
                if (CollectionUtils.isEmpty(piInfoList)) {
                    return new ArrayList<>();
                }
                List<String> userIds = new ArrayList<>();
                piInfoList.forEach(e -> {
                    userIds.add(e.getUserId());
                });
                queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
            }
            queryWrapper.groupBy(OpDeliveryHistory::getUserId).orderByDesc(OpDeliveryHistory::getCreateTime);
            List<OpDeliveryHistory> list = deliveryHistoryService.list(queryWrapper);
            return list.stream().map(OpDeliveryHistory::getUserId).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 查询条件构造
     *
     * @param params
     * @param queryWrapper
     */
    private Boolean createOpDeliveryHistoryWrapper(EntryParam params, LambdaQueryWrapper<OpDeliveryHistory> queryWrapper) {
        // 0 未阅读 1 已阅读  2 不合适 3 通过筛选 4  面试 5已发offer(已录用)6 已入职 7 被过滤
        if (params.getState() != null) {
            if (params.getState() == 0) {
                queryWrapper.in(OpDeliveryHistory::getState, new Integer[]{0, 1});
            } else {
                queryWrapper.eq(OpDeliveryHistory::getState, params.getState());
            }
        }
        if (params.getMaritalStatus() != null) {
            LambdaQueryWrapper<PiInfo> infoQuery = new LambdaQueryWrapper<>();
            infoQuery.eq(PiInfo::getMaritalStatus, params.getMaritalStatus());
            List<PiInfo> piInfoList = piInfoService.list(infoQuery);
            if (CollectionUtils.isEmpty(piInfoList)) {
                return false;
            }
            List<String> userIds = new ArrayList<>();
            piInfoList.forEach(e -> {
                userIds.add(e.getUserId());
            });
            queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
        }
        if (StringUtils.isNotBlank(params.getUserName())) {
            LambdaQueryWrapper<PiInfo> infoQuery = new LambdaQueryWrapper<>();
            infoQuery.like(PiInfo::getName, params.getUserName()).eq(PiInfo::getDelFlag, false);
            List<PiInfo> piInfoList = piInfoService.list(infoQuery);
            if (CollectionUtils.isEmpty(piInfoList)) {
                return false;
            }
            List<String> userIds = new ArrayList<>();
            piInfoList.forEach(e -> {
                userIds.add(e.getUserId());
            });
            queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
        }
        if (params.getMinAge() != null) {
            LambdaQueryWrapper<PiInfo> piInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            String time = cn.com.hhrcw.utils.DateUtil.getYearFirst(params.getMinAge() - 1);
            piInfoLambdaQueryWrapper.le(PiInfo::getBirthday, time).eq(PiInfo::getDelFlag, false);
            List<PiInfo> piInfoList = piInfoService.list(piInfoLambdaQueryWrapper);
            if (CollectionUtils.isEmpty(piInfoList)) {
                return false;
            }
            List<String> userIds = new ArrayList<>();
            piInfoList.forEach(e -> {
                userIds.add(e.getUserId());
            });
            queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
        }
        if (params.getMaxAge() != null) {
            LambdaQueryWrapper<PiInfo> piInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            String time = cn.com.hhrcw.utils.DateUtil.getYearFirst(params.getMaxAge() - 1);
            piInfoLambdaQueryWrapper.ge(PiInfo::getBirthday, time).eq(PiInfo::getDelFlag, false);
            List<PiInfo> piInfoList = piInfoService.list(piInfoLambdaQueryWrapper);
            if (CollectionUtils.isEmpty(piInfoList)) {
                return false;
            }
            List<String> userIds = new ArrayList<>();
            piInfoList.forEach(e -> {
                userIds.add(e.getUserId());
            });
            queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
        }
        if (params.getEduLevel() != null) {
            //0 初中  1 高中 2 中专/中技 3 大专 4 本科 5 硕士 6 MBA/EMBA  7 博士
            LambdaQueryWrapper<CvUserEduInfo> eduQuery = new LambdaQueryWrapper<>();
            eduQuery.eq(CvUserEduInfo::getDelFlag, false).eq(CvUserEduInfo::getEduLevel, params.getEduLevel());
            List<CvUserEduInfo> eduInfos = eduInfoService.list(eduQuery);
            if (CollectionUtils.isEmpty(eduInfos)) {
                return false;
            }
            List<String> userIds = new ArrayList<>();
            eduInfos.forEach(e -> {
                userIds.add(e.getUserId());
            });
            queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
        }
        return true;
    }

    /**
     * 查询条件构造-two
     *
     * @param params
     * @param queryWrapper
     */
    private Boolean createOpDeliveryHistoryWrapperTwo(EntryParam params, LambdaQueryWrapper<OpDeliveryHistory> queryWrapper) {
        if (params.getSex() != null) {
            LambdaQueryWrapper<PiInfo> infoQuery = new LambdaQueryWrapper<>();
            infoQuery.eq(PiInfo::getSex, params.getSex()).eq(PiInfo::getDelFlag, false);
            List<PiInfo> piInfoList = piInfoService.list(infoQuery);
            if (CollectionUtils.isEmpty(piInfoList)) {
                return false;
            }
            List<String> userIds = new ArrayList<>();
            piInfoList.forEach(e -> {
                userIds.add(e.getUserId());
            });
            queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
        }
        if (params.getMinMoney() != null && params.getMaxMoney() != null) {
            List<CvWorkIntention> workIntentions = workIntentionService.lambdaQuery().ge(CvWorkIntention::getMinMoney, params.getMinMoney()).le(CvWorkIntention::getMaxMoney, params.getMaxMoney()).select(CvWorkIntention::getUserId).list();
            if (CollectionUtils.isEmpty(workIntentions)) {
                return false;
            }
            List<String> userIds = new ArrayList<>();
            workIntentions.forEach(e -> {
                userIds.add(e.getUserId());
            });
            queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
        }
        if (StringUtils.isNotBlank(params.getWorkIndustry())) {
            String[] ids = params.getWorkIndustry().split(",");
            String id = ids[ids.length - 1];
            List<CvWorkIntention> workIntentions = workIntentionService.lambdaQuery().like(CvWorkIntention::getWorkIndustry, id).eq(CvWorkIntention::getDelFlag, false).select(CvWorkIntention::getUserId, CvWorkIntention::getResumeId).list();
            if (CollectionUtils.isEmpty(workIntentions)) {
                return false;
            }
            List<String> userIds = new ArrayList<>();
            workIntentions.forEach(e -> {
                CvResume resume = resumeService.getById(e.getResumeId());
                if (resume != null && resume.getLanType() != null && resume.getLanType() == 0) {
                    userIds.add(e.getUserId());
                }
            });
            if (CollectionUtils.isEmpty(userIds)) {
                return false;
            }
            queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
        }
        if (StringUtils.isNotBlank(params.getJobName())) {
            List<RecruitmentPosition> positions = positionService.lambdaQuery().like(RecruitmentPosition::getName, params.getJobName()).select(RecruitmentPosition::getId, RecruitmentPosition::getName).list();
            if (!CollectionUtils.isEmpty(positions)) {
                StringBuilder sql = new StringBuilder("select max(create_time) as create_time,resume_id,user_id  from cv_user_work_info where  ");
                positions.forEach(e -> {
                    sql.append("(position_name like '%" + e.getId() + ",') or ");
                });
                sql.delete(sql.length() - 3, sql.length());
                sql.append(" group by user_id");
                List<CvUserWorkInfo> workIntentions = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(CvUserWorkInfo.class));
                if (CollectionUtils.isEmpty(workIntentions)) {
                    return false;
                }
                Set<String> userIds = new HashSet<>();
                workIntentions.forEach(e -> {
                    CvResume resume = resumeService.getById(e.getResumeId());
                    if (resume != null && resume.getLanType() != null && resume.getLanType() == 0) {
                        userIds.add(e.getUserId());
                    }
                });
                queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 专场人才
     *
     * @param params
     * @return
     */
    public List<String> getUserList(EntryParam params) {
        LambdaQueryWrapper<OpJob> jobLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUserDepart depart = userDepartService.lambdaQuery().eq(SysUserDepart::getUserId, sysUser.getId()).one();
        jobLambdaQueryWrapper.eq(OpJob::getDelFlag, false).eq(OpJob::getCompanyId, depart.getDepId());
        jobLambdaQueryWrapper.eq(OpJob::getBsType, 1).eq(OpJob::getBsId, params.getSsId());
        if (StringUtils.isNotBlank(params.getJobName())) {
            jobLambdaQueryWrapper.like(OpJob::getJobName, params.getJobName());
        }
        SysUserDepart userDepart = userDepartService.lambdaQuery().eq(SysUserDepart::getUserId, sysUser.getId()).one();
        jobLambdaQueryWrapper.eq(OpJob::getCompanyId, userDepart.getDepId());
        List<OpJob> jobs = opJobService.list(jobLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(jobs)) {
            List<String> jobIds = new ArrayList<>();
            jobs.forEach(e -> {
                jobIds.add(e.getId());
            });
            LambdaQueryWrapper<OpDeliveryHistory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OpDeliveryHistory::getDelFlag, false).in(OpDeliveryHistory::getJobId, jobIds);

            /**
             * 0 未阅读 1 已阅读  2 不合适 3 通过筛选 4  面试 5已发offer(已录用)6 已入职 7 被过滤
             */
            if (params.getState() != null) {
                if (params.getState() == 0) {
                    queryWrapper.in(OpDeliveryHistory::getState, new Integer[]{0, 1});
                } else {
                    queryWrapper.eq(OpDeliveryHistory::getState, params.getState());
                }
            }

            if (StringUtils.isNotBlank(params.getUserName())) {
                LambdaQueryWrapper<PiInfo> infoQuery = new LambdaQueryWrapper<>();
                infoQuery.like(PiInfo::getName, params.getUserName()).eq(PiInfo::getDelFlag, false);
                List<PiInfo> piInfoList = piInfoService.list(infoQuery);
                if (CollectionUtils.isEmpty(piInfoList)) {
                    return new ArrayList<>();
                } else {
                    List<String> userIds = new ArrayList<>();
                    piInfoList.forEach(e -> {
                        userIds.add(e.getUserId());
                    });
                    queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
                }
            }

            if (params.getEduLevel() != null) {
                //0 初中  1 高中 2 中专/中技 3 大专 4 本科 5 硕士 6 MBA/EMBA  7 博士
                LambdaQueryWrapper<CvUserEduInfo> eduQuery = new LambdaQueryWrapper<>();
                eduQuery.eq(CvUserEduInfo::getDelFlag, false).eq(CvUserEduInfo::getEduLevel, params.getEduLevel());
                List<CvUserEduInfo> eduInfos = eduInfoService.list(eduQuery);
                if (CollectionUtils.isEmpty(eduInfos)) {
                    return new ArrayList<>();
                } else {
                    List<String> userIds = new ArrayList<>();
                    eduInfos.forEach(e -> {
                        userIds.add(e.getUserId());
                    });
                    queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
                }
            }

            if (params.getMinWorkYear() != null && params.getMaxWorkYear() != null) {

                LambdaQueryWrapper<PiInfo> infoQuery = new LambdaQueryWrapper<>();
                infoQuery.ge(PiInfo::getWorkYears, params.getMinWorkYear()).le(PiInfo::getWorkYears, params.getMaxWorkYear());
                List<PiInfo> piInfoList = piInfoService.list(infoQuery);
                if (CollectionUtils.isEmpty(piInfoList)) {
                    return new ArrayList<>();
                } else {
                    List<String> userIds = new ArrayList<>();
                    piInfoList.forEach(e -> {
                        userIds.add(e.getUserId());
                    });
                    queryWrapper.in(OpDeliveryHistory::getUserId, userIds);
                }

            }
            queryWrapper.notIn(OpDeliveryHistory::getState, new Integer[]{7});
            List<OpDeliveryHistory> list = deliveryHistoryService.list(queryWrapper);
            return list.stream().map(e -> e.getResumeId() + "-" + e.getJobId()).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 候选人
     *
     * @param params
     * @return
     */
    public List<String> candidateList(OpJobParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<OpDeliveryHistory> query = Wrappers.query();
        SysUserDepart userDepart = userDepartService.lambdaQuery().eq(SysUserDepart::getUserId, sysUser.getId()).one();
        query.eq("op_delivery_history.company_id", userDepart.getDepId());
        //屏蔽
        List<OpShielding> shieldingList = opShieldingService.lambdaQuery().eq(OpShielding::getComId, userDepart.getDepId()).eq(OpShielding::getDelFlag, false).list();
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(shieldingList)) {
            query.notIn("op_delivery_history.user_id", shieldingList.stream().map(OpShielding::getUserId).toArray());
        }
        //0 未阅读  1 已阅读 2 不合适 3通过筛选4 面试 5已发offer(已录用) 6 已入职 7 被系统过滤 8未入职9反馈面试结果(通过)10反馈面试结果(不通过)
        int state = 5, stateNine = 9;
        String column = "op_delivery_history.state";
        if (params.getState() == 0) {
            query.in(column, 0, 1);
        } else if (params.getState() == state) {
            query.in(column, new Integer[]{state, stateNine});
        } else {
            query.in(column, params.getState());
        }
        if (StringUtils.isNotBlank(params.getConName()) && params.getState() == state) {
            List<EnContacts> contacts = enContactsService.lambdaQuery().like(EnContacts::getUserName, params.getConName()).eq(EnContacts::getDelFlag, false).list();
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(contacts)) {
                return new ArrayList<>();
            }
            List<String> conIds = new ArrayList<>();
            contacts.forEach(enContacts -> {
                conIds.add(enContacts.getId());
            });
            List<OpEntryHistory> histories = entryHistoryService.lambdaQuery().in(OpEntryHistory::getContactId, conIds).eq(OpEntryHistory::getDelFlag, false).select(OpEntryHistory::getJobId, OpEntryHistory::getUserId).list();
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(histories)) {
                return new ArrayList<>();
            }
            query.and(queryIn -> {
                histories.forEach(e -> {
                    queryIn.or(queryInIn -> queryInIn.eq("op_delivery_history.job_id", e.getJobId()).eq("op_delivery_history.user_id", e.getUserId()));
                });
                return queryIn;
            });
        }
        int aState = 4;
        if (StringUtils.isNotBlank(params.getConName()) && params.getState() == aState) {
            List<EnContacts> contacts = enContactsService.lambdaQuery().like(EnContacts::getUserName, params.getConName()).eq(EnContacts::getDelFlag, false).list();
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(contacts)) {
                return new ArrayList<>();
            }
            List<String> conIds = new ArrayList<>();
            contacts.forEach(enContacts -> {
                conIds.add(enContacts.getId());
            });
            List<OpInterviewHistory> histories = interviewHistoryService.lambdaQuery().in(OpInterviewHistory::getContactId, conIds).eq(OpInterviewHistory::getDelFlag, false).select(OpInterviewHistory::getJobId, OpInterviewHistory::getUserId).list();
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(histories)) {
                return new ArrayList<>();
            }
            query.and(queryIn -> {
                histories.forEach(e -> {
                    queryIn.or(queryInIn -> queryInIn.eq("op_delivery_history.job_id", e.getJobId()).eq("op_delivery_history.user_id", e.getUserId()));
                });
                return queryIn;
            });
        }
        createCandidateListWrapper(params, query);
        //职位名称
        if (StrUtil.isNotBlank(params.getJobName())) {
            query.like("job_name", params.getJobName());
        }
        //学历
        if (params.getEduLevel() != null) {
            query.eq("cv_user_edu_info.edu_level", params.getEduLevel());
        }
        //姓名
        if (StrUtil.isNotBlank(params.getUserName())) {
            query.like("pi_info.name", params.getUserName());
        }
        if (StringUtils.isNotBlank(params.getJobId())) {
            query.eq("op_delivery_history.job_id", params.getJobId());
        }
        Date date = DateUtil.date();
        Date begin = (params.getTimeState() == null || params.getTimeState() == 0) ? DateUtil.offsetMonth(date, -3) : DateUtil.offsetMonth(date, -6);
        query.between("op_delivery_history.create_time", begin, date).eq("op_job.del_flag", false);
        query.orderByDesc("op_delivery_history.create_time");
        params.setPageSize(-1);
        Page<OpDeliveryHistory> page = this.deliveryHistoryService.selectResumeList(params.page(), query);
        return page.getRecords().stream().map(e -> e.getResumeId()).collect(Collectors.toList());
    }

    /**
     * 候选人查询构建
     *
     * @param params
     * @param query
     */
    private void createCandidateListWrapper(OpJobParams params, QueryWrapper<OpDeliveryHistory> query) {
        //职位发布源
        if (params.getSource() != null) {
            switch (params.getSource()) {
                case 1:
                    query.eq("op_job.sys_from", 2).eq("op_job.bs_type", 0);
                    break;
                case 2:
                    query.eq("op_job.sys_from", 2).eq("op_job.bs_type", 1);
                    break;
                case 3:
                    query.eq("op_job.sys_from", 1);
                    break;
                default:
                    break;
            }
        }
        //工作经验
        if (params.getMinExperience() != null && params.getMaxExperience() != null) {
            int maxExperience = 999;
            if (params.getMinExperience() == 0 && params.getMaxExperience() == maxExperience) {
            } else if (params.getMinExperience() == 0 && params.getMaxExperience() == 0) {
                query.isNull("pi_info.job_time");
            } else {
                String start = cn.com.hhrcw.utils.DateUtil.getYearFirst(params.getMaxExperience());
                String end = cn.com.hhrcw.utils.DateUtil.getYearLast(params.getMinExperience());
                query.ge("pi_info.job_time", start).le("pi_info.job_time", end);
            }
        }
    }

    /**
     * 批量简历zip
     *
     * @param userId   userId
     * @param response
     */
    @GetMapping("/zip")
    public void downZip(String userId, EntryParam params, HttpServletResponse response) throws IOException {
        String splitStr = ",";
        if (StrUtil.isBlank(userId)) {
            List<String> users = this.getUserListInfo(params);
            userId = CollUtil.join(users, splitStr);
        }
        if (StringUtils.isNotBlank(userId)) {
            List<String> userIds = new ArrayList<>();
            if (userId.contains(splitStr)) {
                String[] array = userId.split(splitStr);
                userIds.addAll(Arrays.asList(array));
            } else {
                userIds.add(userId);
            }
            if (!CollectionUtils.isEmpty(userIds)) {
                Map<String, File> fileMap = new LinkedHashMap<>();
                for (String id : userIds) {
                    List<CvResume> resumes = resumeService.lambdaQuery().eq(CvResume::getDelFlag, false).eq(CvResume::getUserId, id).list();
                    if (!CollectionUtils.isEmpty(resumes)) {
                        PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, id).one();
                        String fileName = piInfo.getName() + "-" + piInfo.getPhone();
                        resumes.forEach(e -> {
                            if (piInfo != null && StringUtils.isNotBlank(piInfo.getName())) {
                                String key = fileName + "-";
                                File file = null;
                                if (e.getType() == 0) {//在线
                                    if (e.getLanType() == 0) {//中文
                                        String wordUrl = StringUtils.isNotBlank(e.getWordPath()) ? e.getWordPath() : resumeService.getResumeInfo(e.getUserId(), 0, null);
                                        file = new File(wordUrl);
                                        key = key + "中文简历.doc";
                                    } else if (e.getLanType() == 1) {//英文简历若无不主动生成
                                        String wordUrlEn = e.getWordPathEn();
                                        if (StringUtils.isNotBlank(wordUrlEn)) {
                                            file = new File(wordUrlEn);
                                            key = key + "英文简历.doc";
                                        }
                                    }
                                } else if (e.getType() == 1) {
                                    cn.com.hhrcw.entity.File iFile = fileService.getById(e.getFileId());
                                    if (iFile != null) {
                                        file = new File(iFile.getFilePath());
                                        key = key + "附件简历." + iFile.getFileLastName();
                                    }
                                }
                                if (null != file) {
                                    fileMap.put(key, file);
                                }
                            }
                        });

                    }
                }
                if (fileMap.size() > 0) {
                    DownloadToZipUtil.zipFile(response, fileMap, DateUtil.format(new Date(), "yyyyMMddHHmmss") + "简历");
                } else {
                    OutputStream outputStream = response.getOutputStream();
                    outputStream.write(new byte[]{});
                    outputStream.close();
                    outputStream.flush();
                }
            }
        }

    }


    @SneakyThrows
    @GetMapping("/export")
    public void exportResume(String secret, HttpServletResponse response) {
        Assert.notBlank(secret, "导出失败, 没有权限");
        Assert.isTrue(redisTemplate.hasKey(secret), "导出失败, 没有权限");
        ZipSecureFile.setMinInflateRatio(0);
        Map queryMap = (Map) redisTemplate.opsForValue().get(secret);
        Object queryType = queryMap.get("queryType");
        String[] userIds = null;
        String[] deliveryHistoryIds = null;
        //人才库
        if (StrUtil.equals("resumeTalentList", queryType.toString())) {
            IPage<OpDeliveryHistory> opDeliveryHistoryPage = this.deliveryHistoryService.resumeTalentList(new Page(0, -1), queryMap);
            userIds = opDeliveryHistoryPage.getRecords().stream().map(OpDeliveryHistory::getUserId).toArray(String[]::new);
        }
        //候选人
        else {
            IPage<OpDeliveryHistory> opDeliveryHistoryPage = this.deliveryHistoryService.resumeDeliveryList(new Page(0, -1), queryMap);
            deliveryHistoryIds = opDeliveryHistoryPage.getRecords().stream().map(OpDeliveryHistory::getId).toArray(String[]::new);
        }
        response.setContentType("application/octet-stream");
        // 设置在下载框默认显示的文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + URLUtil.encode("简历", StandardCharsets.UTF_8.name()) + ".zip");
        ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
        if (ArrayUtil.isNotEmpty(deliveryHistoryIds)) {
            for (String id : deliveryHistoryIds) {
                byte[] bytes = resumeService.getResumeInfo(id, null);
                if(bytes == null){
                    continue;
                }
                OpDeliveryHistory history = this.deliveryHistoryService.getById(id);
                CvResume resume = this.resumeService.getById(history.getResumeId());
                PiInfo info = this.piInfoService.getById(history.getUserId());
                String phone = info.getPhone();
                String name = info.getName() + "_" + phone + "/" + resume.getResumeName() + "_" + history.getId() + ".docx";
                ZipEntry zipEntry = new ZipEntry(name);
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write(bytes);
                zipOutputStream.flush();
            }
        } else if (ArrayUtil.isNotEmpty(userIds)) {
            for (String id : userIds) {
                byte[] bytes = resumeService.getResumeInfo(null, id);
                if(bytes == null){
                    continue;
                }
                CvResume resume = this.resumeService.lambdaQuery()
                    .eq(CvResume::getDelFlag, 0)
                    .eq(CvResume::getUserId, id)
                    .eq(CvResume::getLanType, 0)
                    .eq(CvResume::getType, 0)
                    .one();
                PiInfo info = this.piInfoService.getById(id);
                String phone = info.getPhone();
                ZipEntry zipEntry = new ZipEntry(info.getName() + "_" + phone + "/" + resume.getResumeName() + ".docx");
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write(bytes);
                zipOutputStream.flush();
            }
        }
        zipOutputStream.finish();
        response.flushBuffer();
    }

    /**
     * 批量简历zip
     *
     * @param resumeId resumeId
     * @param response
     */
    @GetMapping("/zipByresumeId")
    public void downZipByresumeId(String resumeId, EntryParam params, OpJobParams jobParams, HttpServletResponse response) throws IOException {
        String joinStr = ",";
        if (StrUtil.isBlank(resumeId)) {
            List<String> users = StrUtil.isNotBlank(params.getSsId()) ? this.getUserList(params) : this.candidateList(jobParams);
            resumeId = CollUtil.join(users, joinStr);
        }
        if (StringUtils.isNotBlank(resumeId)) {
            List<String> resumeIds = new ArrayList<>();
            if (resumeId.contains(joinStr)) {
                String[] array = resumeId.split(joinStr);
                resumeIds.addAll(Arrays.asList(array));
            } else {
                resumeIds.add(resumeId);
            }
            if (!CollectionUtils.isEmpty(resumeIds)) {
                Map<String, File> fileMap = new LinkedHashMap<>();
                for (String r : resumeIds) {
                    // 前端组合传参  若需要投递职位信息 s = 用户id-职位id
                    String[] split = r.split("-");
                    String id = split[0];
                    String jobId = split[1];
                    CvResume resumes = resumeService.lambdaQuery().eq(CvResume::getDelFlag, false).eq(CvResume::getId, id).one();
                    OpJob opJob = this.opJobService.getById(jobId);
                    if (null != resumes) {
                        PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, resumes.getUserId()).one();
                        String fileName = piInfo.getName() + "-" + piInfo.getPhone();
                        String key = fileName + "-" + opJob.getJobName();
                        File file = null;
                        if (resumes.getType() == 0) {
                            if (resumes.getLanType() == 0) {
                                String wordUrl = StringUtils.isNotBlank(resumes.getWordPath()) && StringUtils.isBlank(jobId)
                                    ? resumes.getWordPath() : resumeService.getResumeInfo(resumes.getUserId(), 0, jobId);
                                file = new File(wordUrl);
                                key = key + "中文简历.doc";

                            } else {
                                String wordUrlEn = resumes.getWordPathEn();
                                if (StringUtils.isNotBlank(wordUrlEn)) {
                                    file = new File(wordUrlEn);
                                    key = key + "英文简历.doc";
                                }
                            }
                        } else if (resumes.getType() == 1) {
                            cn.com.hhrcw.entity.File iFile = fileService.getById(resumes.getFileId());
                            if (iFile != null) {
                                file = new File(iFile.getFilePath());
                                key = key + "附件简历." + iFile.getFileLastName();
                            }
                        }
                        if (null != file) {
                            fileMap.put(key, file);
                        }
                    }
                }
                if (fileMap.size() > 0) {
                    DownloadToZipUtil.zipFile(response, fileMap, DateUtil.format(new Date(), "yyyyMMddHHmmss") + "简历");
                } else {
                    OutputStream outputStream = response.getOutputStream();
                    outputStream.write(new byte[]{});
                    outputStream.close();
                    outputStream.flush();
                }
            }
        }

    }
}
